package com.lmx.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lmx.project.common.BaseResponse;
import com.lmx.project.common.ErrorCode;
import com.lmx.project.common.ResultUtils;
import com.lmx.project.exception.BusinessException;
import com.lmx.project.model.dto.awards.AwardsAddRequest;
import com.lmx.project.model.dto.awards.AwardsQueryRequest;
import com.lmx.project.model.dto.awards.AwardsUpdateRequest;
import com.lmx.project.model.entity.Awards;
import com.lmx.project.model.entity.Users;
import com.lmx.project.model.vo.UsersVo;
import com.lmx.project.service.AwardsService;
import com.lmx.project.service.UsersService;
import com.lmx.project.untils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.UUID;


/**
 * 获奖记录的增删改查
 */
@RestController
@RequestMapping("award")
@ResponseBody
@Slf4j
public class AwardsController {
    @Resource
    private AwardsService awardsService;
    //    @Resource
//    private FileUntil fileUntil;
    private long imagesize = 4 * 1024 * 1024;

    @Resource
    private UsersService usersService;

    @Resource
    private FileUtil fileUtil;


    String avarddir = "avard/";

    /**
     * 增加奖项记录 管理员与普通用户都可以，普通用户修改自己的
     */
    @PostMapping
    public BaseResponse<Long> addAeard(AwardsAddRequest awardsAddRequest, HttpServletRequest request) throws IOException {
//        属性是否合法
        if (awardsAddRequest.getAwardname() == null || awardsAddRequest.getAwardname().equals("")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请输入奖项名称");
        }
        if (awardsAddRequest.getCompitionid() == null || awardsAddRequest.getCompitionid() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请选择关联竞赛");
        }


        if (awardsAddRequest.getStatu() == 1 && awardsAddRequest.getImagefile() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请上传获奖整数图片");
        }

        if (awardsAddRequest.getStatu() == null) {
            awardsAddRequest.setStatu(0);
        }

//        判断是否登录获取值
        UsersVo data = usersService.getUserCurrent(request);

//        Users data = usersByid.getData();
        if (data == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Long id = data.getId(); //当前用户的id

        Awards awards = new Awards();
        BeanUtils.copyProperties(awardsAddRequest, awards);
        //        管理员
        if (data.getPermissionlevel() != 0) {
            if (awardsAddRequest.getUserid() == null || awardsAddRequest.getUserid() == 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "请指定用户");
            } else {
                awards.setUserid(awardsAddRequest.getUserid());
            }
        } else {
            awards.setUserid(data.getId());
        }
//     设置图片
        if (awardsAddRequest.getImagefile() != null) {
            if (awardsAddRequest.getImagefile().getSize() > imagesize) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片大小需小于4MB");
            }
            MultipartFile imagefile = awardsAddRequest.getImagefile();

//
//            String originalFilename = imagefile.getOriginalFilename();
////            后缀名
//            String substring = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
//
//            String resultfilename = UUID.randomUUID().toString().replace("-", "");


//            String b = fileUntil.saveFile(imagefile.getInputStream(), imagefile + resultfilename + substring);

            String b = fileUtil.saveMultipartFile(imagefile, avarddir);
            if (StringUtils.isNotBlank(b)) {
                awards.setImageurl(b);
            } else {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片上传错误");
            }
        }

        boolean save = awardsService.save(awards);
        if (save) {
            return ResultUtils.success(awards.getId());
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或者稍后重试");
        }
    }


    /**
     * 修改奖项记录 管理员与普通用户都可以，普通用户修改自己的
     */
    @PutMapping
    public BaseResponse<Boolean> updateAeard(AwardsUpdateRequest awardsUpdateRequest, HttpServletRequest request) throws IOException {

        if (awardsUpdateRequest.getId() == null || awardsUpdateRequest.getId() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请输入id");
        }

        Awards byId = awardsService.getById(awardsUpdateRequest.getId());

//        是否登录，是否管理员
        //        判断是否登录获取值
        UsersVo data = usersService.getUserCurrent(request);

//        Users data = usersByid.getData();
        if (data == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Long id = data.getId(); //当前用户的id
//        不是管理员，不是当前登录用户
        if (!id.equals(byId.getUserid()) && data.getPermissionlevel() == 0) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        Awards awards = new Awards();
        BeanUtils.copyProperties(awardsUpdateRequest, awards);
        if (awardsUpdateRequest.getStatu() == 1 && awardsUpdateRequest.getImagefile() != null) {
            if (awardsUpdateRequest.getImagefile().getSize() > imagesize) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片大小需小于4MB");
            }
//            删除原有图片
            //        删除云存储中的图片
            String fileurl = byId.getImageurl();
//            String[] split = fileurl.split("/");
//            String key = split[split.length - 2] + "/" + split[split.length - 1];
//            boolean deletefile = fileUntil.deletefile(key);
            fileUtil.removeFile(fileurl);

//            增加新的图片
            MultipartFile imagefile = awardsUpdateRequest.getImagefile();


            String originalFilename = imagefile.getOriginalFilename();
//            后缀名
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());

            String resultfilename = UUID.randomUUID().toString().replace("-", "");


            String b = fileUtil.saveMultipartFile(imagefile, avarddir);
            if (b != null) {
                awards.setImageurl(b);
            } else {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片上传错误");
            }

        }


        boolean b = awardsService.updateById(awards);
        if (b) {
            return ResultUtils.success(b);
        } else {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或者稍后重试");
        }
    }

    /**
     * 删除参赛记录
     */

    @DeleteMapping
    public BaseResponse<Boolean> deleteAwaed(Long id, HttpServletRequest request) throws IOException {

//        id是否正确
        if (id == null || id == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
//        查询数据库中的记录
        Awards byId = awardsService.getById(id);
        if (byId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该奖项记录不存在");
        }
        Long userid = byId.getUserid();
//        获取当前用户
//        BaseResponse<Users> usersByid = usersController.getUsersByid(request);
        UsersVo data = usersService.getUserCurrent(request);
        if (data == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Long id1 = data.getId();//当前登录的用户
//        是否是当前用户的参赛记录或者是管理员
        if (userid.equals(id1) || data.getPermissionlevel() != 0) {
            //        删除图片
//            String imageurl = byId.getImageurl();
//            String[] split = imageurl.split("/");
//            String key = split[split.length - 2] + "/" + split[split.length - 1];
//            boolean deletefile = fileUntil.deletefile(key);
            fileUtil.removeFile(byId.getImageurl());
//            if (!deletefile) {
//                log.info("图片删除失败");
////                throw new BusinessException(ErrorCode.PARAMS_ERROR, "删除失败，请联系管理员或稍后重试");
//            }
//        删除数据库中的记录
            boolean b = awardsService.removeById(id);
            if (b) {
                return ResultUtils.success(b);
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "请联系管理员或者稍后重试");
            }
        } else {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }


    /**
     * 根据竞赛id或成员id查询
     */
    @GetMapping
    public BaseResponse<List<Awards>> getListByIds(AwardsQueryRequest awardsQueryRequest) {
        LambdaQueryWrapper<Awards> queryWrapper = new LambdaQueryWrapper<>();
        if (awardsQueryRequest != null) {
            if (awardsQueryRequest.getCompitionid() != null && awardsQueryRequest.getCompitionid() != 0) {
                queryWrapper.eq(Awards::getCompitionid, awardsQueryRequest.getCompitionid());
            }
            if (awardsQueryRequest.getUserid() != null && awardsQueryRequest.getUserid() != 0) {
                queryWrapper.eq(Awards::getUserid, awardsQueryRequest.getUserid());
            }
        }
        List<Awards> list = awardsService.list(queryWrapper);

        String preUrl = fileUtil.getPreUrl();
        list.stream().forEach(awards -> {
            awards.setImageurl(preUrl + awards.getImageurl());
        });
        return ResultUtils.success(list);
    }
}
